<?php

namespace app\admin\controller;

use app\model\Menu as MenuModel;
use app\admin\validate\menu\Menu as MenuValidate;
use think\Db;
use app\service\menu\MenuService;
use think\Exception;

class Menu extends BaseController
{
    private static $parentMenu = 'menu/adminmenuindex';

    //region 后台菜单管理

    /**
     * 后台菜单列表
     * @return mixed
     */
    public function adminMenuIndex()
    {
        $menuService = new MenuService();
        $menuList = $menuService->getMenuList();
        $this->assign([
            'menu_list' => htmlspecialchars_decode($menuList),
            'parentMenu' => self::$parentMenu,
            'currentMenu' => 'menu/adminmenuindex'
        ]);
        return $this->fetch('adminmenuindex');
    }

    /**
     * 添加后台菜单
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminMenuAdd()
    {
        $model = new MenuModel();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!isset($data['menu_status'])) {
                $data['menu_status'] = 0;
            }
            $validate = new MenuValidate();
            if (!$validate->check($data)) {
                $this->doRedirect($validate->getError(), "2");
            }
            $data['menu_is_admin'] = 1; // 是否为后台权限
            $data['menu_page_url'] = strtolower($data['menu_page_url']); //把权限URL改成小写
            $data['create_time'] = time();
            $model->data($data)->allowField(true)->save();
            $this->doRedirect('添加成功！', '1', 'menu/adminmenuindex');
        };
        $parentId = $this->request->param('parentId');
        if (empty($parentId)) {
            $parentId = 0;
        }
        $parentModel = Db::table('aya_menu')
            ->where('menu_status', '<>', -1)
            ->where('menu_id', '=', $parentId)
            ->find();
        $parentName = '一级菜单';
        $depth = 1;
        if ($parentModel) {
            $parentName = $parentModel['menu_name'];
            $depth = $parentModel['menu_depth'] + 1;
        }
        if ($depth > 3) {
            $this->doRedirect('只能添加三级菜单', "2");
        }
        $this->assign([
            'menu_parent_id' => $parentId,
            'menu_parent_name' => $parentName,
            'menu_depth' => $depth,
            'parentMenu' => self::$parentMenu,
            'currentMenu' => 'menu/adminmenuindex'
        ]);
        return $this->fetch('adminmenuadd');
    }

    /**
     * 后台权限编辑
     * @return mixed
     * @throws \Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function adminMenuEdit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!isset($data['menu_status'])) {
                $data['menu_status'] = 0;
            }
            $model = new MenuModel();
            $validate = new MenuValidate();
            if (!$validate->check($data)) {
                $this->doRedirect($validate->getError(), "2");
            }
            $data['menu_page_url'] = strtolower($data['menu_page_url']); //把权限URL改成小写
            $data['update_time'] = time();
            Db::startTrans();
            try {
                $model->allowField(true)->save($data, ['menu_id' => $data['id']]);
                $list = $this->getChangeMenuList($data['id'], $data['menu_status']);
                $model->allowField(true)->saveAll($list);
                Db::commit();
                $this->doRedirect('编辑成功！', '1', 'menu/adminmenuindex');
            } catch (Exception $e) {
                Db::rollback();
                $this->doRedirect('编辑失败！错误原因是' . $e->getMessage(), '2', 'menu/adminmenuindex');
            }

        }
        $id = $this->request->param('id');
        if (empty($id)) {
            $this->doRedirect('参数错误，请重试！', '2');
        }
        $menu = Db::table('aya_menu')->where('menu_status', '<>', -1)
            ->where('menu_id', '=', $id)
            ->find();
        if (empty($menu)) {
            $this->doRedirect('找不到id为' . $id . '的数据，请重试！', '2');
        }
        $menuService = new MenuService();
        $parentMenu = $menuService->getById($menu['menu_id']);
        $parentName = '一级菜单';
        if (!empty($parentMenu)) {
            $parentName = $parentMenu['menu_name'];
        }
        $this->assign([
            'model' => $menu,
            'parentName' => $parentName,
            'parentMenu' => self::$parentMenu,
            'currentMenu' => 'menu/adminmenuindex'
        ]);
        return $this->fetch('adminmenuedit');
    }

    //endregion

    //region 删除菜单

    /**
     * 修改状态（前后台通用）
     * @throws \Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changeStatus()
    {
        $id = $this->request->param('id');
        $status = $this->request->param('status');
        if (empty($id) || !in_array($status, [-1, 0, 1])) {
            $this->doRedirect('参数错误，请重试！', '2');
        }
        $model = new MenuModel();
        $list = $this->getChangeMenuList($id, $status);
        $model->allowField(true)->saveAll($list);
        $this->doRedirect('操作成功！', '1');
    }

    /**
     * 获取要修改状态的菜单
     * @param $id
     * @param $status
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getChangeMenuList($id, $status)
    {
        $menu = Db::table('aya_menu')
            ->where('menu_id', '=', $id)
            ->where('menu_status', '<>', -1)
            ->find();
        if (!$menu) {
            $this->doRedirect('找不到ID为' . $id . '的数据，请重试！', '2');
        }
        $list = [];
        $menu['menu_status'] = $status;
        $menu['update_time'] = time();
        array_push($list, $menu);
        $childrenMenu = Db::table('aya_menu')
            ->where('menu_parent_id', '=', $id)
            ->where('menu_status', '<>', -1)
            ->select();
        if (!empty($childrenMenu)) {
            foreach ($childrenMenu as $key => $value) {
                $childrenMenu[$key]['menu_status'] = $status;
                $childrenMenu[$key]['update_time'] = time();
                array_push($list, $childrenMenu[$key]);
                $grandChildrenMenu = Db::table('aya_menu')
                    ->where('menu_parent_id', '=', $value['menu_id'])
                    ->where('menu_status', '<>', -1)
                    ->select();
                if (!empty($grandChildrenMenu)) {
                    foreach ($grandChildrenMenu as $grandKey => $grandValue) {
                        $grandChildrenMenu[$grandKey]['menu_status'] = $status;
                        $grandChildrenMenu[$grandKey]['update_time'] = time();
                        array_push($list, $grandChildrenMenu[$grandKey]);
                    }
                }

            }
        }
        return $list;
    }

    //endregion 删除菜单
}